<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TreeController extends Controller
{
    private $config = [
        'db_path'   => '/data/backup/mysql/',
        'site_path' => '/data/backup/site_root/',
    ];

    public function db()
    {
        $title = '数据库备份管理';
        if ($this->isPost()) {
            $nodes = self::getTree($this->config['db_path'], false);
            mylog($nodes, 'nodes');
            return $this->setJson(0, 'ok', $nodes);
        }
        return view('tree.db', compact('title'));
    }

    public function site()
    {
        $title = '站点备份管理';
        if ($this->isPost()) {
            $nodes = self::getTree($this->config['site_path'], false);
            return $this->setJson(0, 'ok', $nodes);
        }
        return view('tree.site', compact('title'));
    }

    /**
     * 下载
     */
    public function download()
    {
        $md5  = $this->request->input('md5', '');
        $file = Cache::get($md5);
        if (file_exists($file)) {
            sg_download($file);
        } else {
            return '文件不存在';
        }
    }

    /**
     * 获取目录下的结构
     * @param $data_dir string 必须以/结尾
     * @param $spread bool 是否展开
     * @return array
     */
    public static function getTree($data_dir, $spread = false)
    {
        $list = glob($data_dir . '*');
        rsort($list);
        $tree = [];
        if ($list) {
            foreach ($list as $child_dir) {
                $tmp             = [];
                $name            = pathinfo($child_dir, PATHINFO_BASENAME);
                $tmp['name']     = date('Y年m月d日', strtotime($name));
                $tmp['spread']   = $spread;
                $tmp['children'] = [];
                $ls              = glob($child_dir . '/*');
                if ($ls) {
                    $total = 0;
                    foreach ($ls as $file) {
                        if(is_file($file)) {
                            $size        = filesize($file);
                            $total       += $size;
                            $size_format = size2mb($size);
                            $md5         = md5($file);
                            Cache::put($md5, $file, Carbon::now()->addDay(1));
                            $tmp['children'][] = [
                                'name'   => pathinfo($file, PATHINFO_BASENAME) . '(' . $size_format . ')',
                                'spread' => $spread,
                                'md5'    => $md5,
                            ];
                        }
                    }
                    $tmp['name'] .= '(' . size2mb($total) . ')';
                }
                $tree[] = $tmp;
            }
        }
        return $tree;
    }

}
